//
//  NSSinSignal.m
//  SpeedTest
//
//  Created by Han Mingjie on 2020/4/3.
//  Copyright © 2020 MingJie Han. All rights reserved.
//

#import "NSSinSignal.h"

@implementation NSSinSignal
@synthesize delegate;

-(void)start_signal{
    [NSThread detachNewThreadSelector:@selector(makeECG_thread) toTarget:self withObject:nil];
}

-(void)makeECG_thread{
    int flow_num = 0;
    float ECG_rate = 446.f;
    NSArray *ecg_freq = @[[NSNumber numberWithFloat:1.f],
    [NSNumber numberWithFloat:2.f],
    [NSNumber numberWithFloat:4.f],
    [NSNumber numberWithFloat:8.f],
    [NSNumber numberWithFloat:16.f],
    [NSNumber numberWithFloat:32.f],
    [NSNumber numberWithFloat:1.f],
    [NSNumber numberWithFloat:1.5f],
    [NSNumber numberWithFloat:2.f],
    [NSNumber numberWithFloat:2.5f],
    [NSNumber numberWithFloat:3.f],
    [NSNumber numberWithFloat:3.5f]];
    while (YES) {
        NSDate *last_date = [NSDate date];
        NSMutableArray <NSMutableArray <NSNumber *>*>*ecg_array = [[NSMutableArray alloc] init];
        for (int i=0;i<ecg_freq.count;i++){
            NSMutableArray *ecg_lead = [[NSMutableArray alloc] init];
            [ecg_array addObject:ecg_lead];
        }
        for (int i=0;i<80;i++){
            for (int j=0;j<ecg_freq.count;j++){
                float single_freq = [[ecg_freq objectAtIndex:j] floatValue];
                NSMutableArray *ecg_lead = [ecg_array objectAtIndex:j];
                double v = 1000.f * sin( 2 * 3.14 * single_freq * flow_num/ECG_rate);
                [ecg_lead addObject:[NSNumber numberWithDouble:v]];
            }
            flow_num ++;
        }
        
        //put out those result
        [delegate signal:ecg_array];
        
        //80.f 是V&H 解码后的单次送出数量
        [NSThread sleepUntilDate:[NSDate dateWithTimeInterval:80.f/ECG_rate sinceDate:last_date]];
    }
    return;
}
@end
